const userNameElement = document.getElementById('userName')
const roomNameElement = document.getElementById('roomName')
const connectBtnElement = document.getElementById('connectBtn')
const outputTextElement = document.getElementById('outputText')
const inputTextElement = document.getElementById('inputText')
const sendBtnElement = document.getElementById('sendBtn')


let socket
let roomName
let userName

connectBtnElement.onclick = e => {
    roomName = roomNameElement.value
    userName = userNameElement.value
    socket = io.connect()

    socket.on("joined", (room, id) => {
        console.log(`${id} join the room:${room}`)
    })

    socket.on('message', (room, id, message) => {
        outputTextElement.value += `${id}:${message}\n`
    })

    // join the room
    socket.emit('join', roomName, userName)
}


sendBtnElement.onclick = e => {
    const value = inputTextElement.value
    socket.emit('message', roomName, userName, value)
    inputTextElement.value = ""
}

window.onbeforeunload = (e) => {
    socket.emit('leave', roomName, userName)
    return true
}